<script setup>
import { ref, watch,watchEffect,computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import axios from 'axios'

import { useUserStore } from '@/stores/user'
import { usePostStore } from '@/stores/post'
import { useUiStore } from '@/stores/ui'
import CommentList from '@/components/CommentList.vue' // 路径视你的项目结构调整


const route = useRoute()
const router = useRouter()
const postId = computed(() => Number(route.params.id))

const userStore = useUserStore()
const postStore = usePostStore()
const uiStore = useUiStore()

const { user,isExpert,isAdmin,isLogin } = storeToRefs(userStore)
const { currentPost: post } = storeToRefs(postStore) // ✅ 响应式绑定



const newComment = ref('')
const loading = ref(true)

const isQnA = computed(() => post.value?.postType === 'QUESTION')

const loadPost = async () => {
  loading.value = true
  await postStore.fetchPostDetail(postId.value)
  loading.value = false

  // ✅ 打印评论数据看看结构
  console.log('🔍 当前评论列表:', post.value?.comments)
}



watch(postId, () => loadPost(), { immediate: true })
watchEffect(() => {
  console.log('🧩 user:', user.value)
  console.log('🧩 role:', user.value?.role)
  console.log('🧩 isExpert:', isExpert.value)
})


const toggleLike = async () => {
  if (!isLogin) {
    uiStore.showNotification('请先登录')
    return
  }
  await postStore.toggleLike(post.value.knowledgeId, user.value.userId)
  await loadPost()
}

const toggleFavorite = async () => {
  if (!isLogin) {
    uiStore.showNotification('请先登录')
    return
  }
  await postStore.toggleFavorite(post.value.knowledgeId, user.value.userId)
  await loadPost()
}

const isPostLiked = () => {
  const userId = user.value?.userId
  return post.value?.likedBy?.includes(String(userId))
}

const isPostFavorited = () => {
  const userId = user.value?.userId
  return post.value?.favoritedBy?.includes(String(userId))
}

const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit'
  })
}

const isLoggedIn = computed(() => !!user.value)

const sharePost = () => {
  uiStore.showNotification('分享功能暂未开放')
}

const submitComment = async () => {
  if (!user.value) {
    router.push({ name: 'Login', query: { redirect: { name: 'PostDetail', params: { id: postId.value } } } })
    return
  }
  const content = newComment.value.trim()
  if (!content) {
    uiStore.showNotification('评论不能为空')
    return
  }
  const payload = {
    knowledgeId: post.value.knowledgeId,
    userId: user.value.userId,
    content: newComment.value.trim()
  }
  await postStore.addComment(payload)
  newComment.value = ''
  await loadPost()
}

const avatarUrl = computed(() => post.value?.avatar || '/default-avatar.png')

const replyToComment = (id) => {
  uiStore.showNotification('回复功能开发中')
}

const getUserAvatar = (username) => {
  return 'https://picsum.photos/200/200?random=1'
}

const goBack = () => router.back()
</script>

<template>
  <div class="post-detail">
    <!-- 加载状态或错误提示 -->
    <div v-if="loading || !post" class="loading-container">
      <div v-if="loading" class="spinner"></div>
      <div v-else class="error-message">
        <p>帖子不存在或已被删除</p>
        <button @click="goBack">返回</button>
      </div>
    </div>

    <!-- 帖子详情 -->
    <div v-else class="post-detail-content">
      <div class="back-button-container">
        <button class="back-button" @click="goBack">
          <i class="fa fa-arrow-left"></i> 返回上一页
        </button>
      </div>
      <!-- 帖子头部 -->
      <div class="post-header">
        <h1>{{ post.title }}</h1>
        <div class="user-info">
          <img :src="avatarUrl" class="avatar" />
          <div>
            <div class="username">{{ post.nickname }}</div>
            <div class="post-time">{{ formatDate(post.createdAt) }}</div>
          </div>
        </div>
        <div class="post-stats">
          <div class="stat-item">
            <i class="fa fa-thumbs-up"></i>
            <span>{{ post.likes }}</span>
          </div>
          <div class="stat-item">
            <i class="fa fa-comment"></i>
            <span>{{ post.comments?.length || 0 }}</span>
          </div>
          <div class="stat-item">
            <i class="fa fa-eye"></i>
            <span>{{ post.views || 0 }}</span>
          </div>
        </div>
      </div>

      <!-- 帖子内容 -->
      <div class="post-content">
        <div v-html="post.content"></div>
        <div class="post-images" v-if="post.images && post.images.length > 0">
          <img
            v-for="(image, index) in post.images"
            :key="index"
            :src="image"
            alt="帖子图片"
            class="post-image"
          />
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="post-actions">
        <!-- 点赞按钮 -->
        <button @click="toggleLike" class="action-button" :disabled="!isLoggedIn">
          <i class="fa fa-thumbs-up" :class="{ liked: isPostLiked() }"></i>
          <span>{{ isPostLiked() ? '已点赞' : '点赞' }}</span>
        </button>
        <!-- 收藏按钮 -->
        <button @click="toggleFavorite" class="action-button" :disabled="!isLoggedIn">
          <i class="fa fa-star" :class="{ favorited: isPostFavorited() }"></i>
          <span>{{ isPostFavorited() ? '已收藏' : '收藏' }}</span>
        </button>
        <button @click="sharePost" class="action-button">
          <i class="fa fa-share-alt"></i>
          <span>分享</span>
        </button>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <h3>评论 ({{ post.comments?.length || 0 }})</h3>

        <!-- 登录 + （不是问答 或者是专家）才显示评论框 -->
        <div v-if="isLogin && (!isQnA || isExpert)" class="comment-form">
          <textarea
            v-model="newComment"
            placeholder="发表评论..."
            rows="3"
            class="comment-input"
          ></textarea>
          <button
            @click="submitComment"
            :disabled="!newComment.trim()"
            class="comment-submit"
          >
            发表评论
          </button>
        </div>

        <!-- 未登录提示 -->
        <div v-else class="login-prompt">
          <p>请先 <router-link to="/login">登录</router-link> 后再评论</p>
        </div>
        <!-- 已登录但无权限（问答+非专家） -->
        <div v-if="isLogin && isQnA && !isExpert" class="login-prompt">
          <p>⚠️ 只有专家用户才能在问答帖中发表评论</p>
        </div>

        <!-- 评论列表 -->
        <CommentList :comments="post.comments || []" @reply="replyToComment" />
      </div>
    </div>
  </div>
</template>




<style scoped>
/* 样式与之前保持一致，此处省略重复代码 */
.post-detail-content {
  max-width: 720px;
  margin: 40px auto;
  background-color: #ffffff;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  font-family: 'Helvetica Neue', sans-serif;
}

.post-header h1 {
  font-size: 28px;
  margin-bottom: 20px;
  font-weight: bold;
  text-align: center;
  color: #333;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
  justify-content: center;
}

.user-info .avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 2px solid #eee;
  object-fit: cover;
}

.username {
  font-size: 18px;
  font-weight: 600;
  color: #444;
}

.post-time {
  font-size: 13px;
  color: #888;
}

.post-stats {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 20px 0;
  font-size: 15px;
  color: #666;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.post-content {
  padding-top: 20px;
  line-height: 1.8;
  color: #333;
}

.post-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 25px;
}

.action-button {
  background-color: #f5f5f5;
  border: none;
  padding: 10px 18px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
}

.action-button:hover {
  background-color: #e0e0e0;
}
.action-button:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
.fa.liked {
  color: #2196F3;
}

.fa.favorited {
  color: #FF9800;
}

.comments-section {
  margin-top: 50px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.comments-section h3 {
  margin-bottom: 15px;
}
.back-button-container {
  margin-bottom: 20px;
}

.back-button {
  background-color: #f0f0f0;
  color: #333;
  border: none;
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #ddd;
}

.back-button i {
  margin-right: 6px;
}
.comment-form {
  background-color: #fafafa;
  border: 1px solid #ddd;
  border-radius: 10px;
  padding: 16px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.comment-input {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 10px 12px;
  resize: none;
  font-size: 14px;
  font-family: inherit;
  outline: none;
  transition: border 0.2s;
}

.comment-input:focus {
  border-color: #409EFF;
}

.comment-submit {
  margin-top: 12px;
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  float: right;
  transition: background-color 0.3s;
}

.comment-submit:hover {
  background-color: #2e8ae6;
}

.comment-submit:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>